package com.lan.app.utils;

import com.alibaba.fastjson.JSONObject;
import com.lan.ot.ClazzOt;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Repository
public class SqlDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public int save(String sql, Map param, boolean isRtn) {
        SqlParameterSource ps = new MapSqlParameterSource(param);
        if (isRtn) {
            KeyHolder keyHolder = new GeneratedKeyHolder();
            namedParameterJdbcTemplate.update(sql, ps, keyHolder);
            return keyHolder.getKey().intValue();
        } else {
            return namedParameterJdbcTemplate.update(sql, ps);
        }
    }


    public int update(String sql, Map param) {
        return namedParameterJdbcTemplate.update(sql, param);
    }

    public Object select(String sql, Map param) {
        List<Map<String, Object>> list = namedParameterJdbcTemplate.queryForList(sql, param);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);

    }

    public Object selectList(String sql, Map param) {
        List<Map<String, Object>> list = namedParameterJdbcTemplate.queryForList(sql, param);
        return list;
    }


}
